package _binary_tree

import common.TreeNode
import org.junit.Assert
import org.junit.Test
import java.util.*

/**
 * https://leetcode.cn/problems/deepest-leaves-sum/description
 *
 * ```
 * 1302. 层数最深叶子节点的和
 * 给你一棵二叉树的根节点 root ，请你返回 层数最深的叶子节点的和 。
 *
 * 示例 1：
 * 输入：root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
 * 输出：15
 *
 * 示例 2：
 * 输入：root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
 * 输出：19
 *
 * 提示：
 * 树中节点数目在范围 [1, 104] 之间。
 * 1 <= Node.val <= 100
 * ```
 */
class leetcode_1302 {
    @Test
    fun test_1() {
        val n1 = TreeNode(1)
        val n2 = TreeNode(2)
        val n3 = TreeNode(3)
        val n4 = TreeNode(4)
        val n5 = TreeNode(5)
        val n6 = TreeNode(6)
        val n7 = TreeNode(7)
        val n8 = TreeNode(8)
        val root = n1
        n1.left = n2
        n1.right = n3

        n2.left = n4
        n2.right = n5

        n3.right = n6

        n4.left = n7

        n6.right = n8

        val actual = deepestLeavesSum(root)
        val expected = 15
        Assert.assertEquals(expected, actual)
    }

    fun deepestLeavesSum(root: TreeNode?): Int {
        /**
        题型： 二叉树的层级遍历
        思路：
        遍历每一层求出sum，最后一层的sum 就是 目标sum
         */
        // 终止条件
        if (null == root) {
            return 0
        }

        // 1 初始化队列
        val queue: LinkedList<TreeNode> = LinkedList()
        queue.offer(root)

        // 2 外层循环
        var sum: Int = 0
        while (!queue.isEmpty()) {
            var size: Int = queue.size
            var tempSum = 0

            // 3 内层循环：本层循环
            while (size-- > 0) {
                val node = queue.poll()
                tempSum = tempSum + node.`val`
                node.left?.let { queue.offer(it) }
                node.right?.let { queue.offer(it) }
            }

            // 4 收集本层结果
            sum = tempSum
        }
        return sum
    }
}